﻿using System.IO;
using System.Xaml;

namespace XtremeMvvm
{
    public static class LooseXaml
    {
        public static object Load(string filePath)
        {
            if (File.Exists(filePath))
            {
                using (StreamReader streamReaderFromFile = new StreamReader(filePath))
                {
                    return ConvertXamlToObjectGraph(streamReaderFromFile.BaseStream);
                }
            }
            else
            {
                throw new FileNotFoundException("Loose XAML file was not found.", filePath);
            }
        }

        private static object ConvertXamlToObjectGraph(Stream stream)
        {
            using (XamlXmlReader reader = new XamlXmlReader(stream, System.Windows.Markup.XamlReader.GetWpfSchemaContext()))
            {
                using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
                {
                    while (reader.Read())
                    {
                        writer.WriteNode(reader);
                    }
                    return writer.Result;
                }
            }
        }
    }
}